package handler

import (
	"log"
	/*"net/http"*/
	"fmt"
	db "echo_prj/db"
	"github.com/labstack/echo"
	/*"encoding/json"*/
	"strconv"
)

//获取产品
func GetProduct(c echo.Context) error  {
	var a = Res{}
	page := c.FormValue("page")
	limit := c.FormValue("limit")
	
	pageNum,err := strconv.Atoi(page)
	limitNum,err := strconv.Atoi(limit)
	if err != nil{
		log.Println("GetProduct,err=",err)
		a.Code=-1
		a.Msg="参数错误"
		return c.JSON(200,a)
	}
	ps,err := db.GetProduct(pageNum,limitNum)
	if err != nil{
		log.Println("GetProduct,err=",err)
		a.Code=-1
		a.Msg=err.Error()
	}else{
		a = Res{
			Code:200,
			Msg:"",
			Result:ps,
		}
	}
	return c.JSON(200,a)
}
//发布产品
func PostProduct(c echo.Context) error {
	var a = Res{}
	title := c.FormValue("prodTitle")
	desc := c.FormValue("prodDesc")
	weight := c.FormValue("prodWeight")
	imgId := c.FormValue("prodImg")
	qrcodeId := c.FormValue("prodQrCode")
	
	id,err := db.PostProduct(title,desc,weight,imgId,qrcodeId)
	if err != nil{
		log.Println("PostProduct,err=",err)
		a.Code=-1
		a.Msg=err.Error()
	}else{
		a = Res{
			Code:200,
			Msg:"",
			Result:id,
		}
	}
	return c.JSON(200,a)
}
//修改产品
func EditProduct(c echo.Context) error {
	var a = Res{}
	title := c.FormValue("prodTitle")
	desc := c.FormValue("prodDesc")
	weight := c.FormValue("prodWeight")
	imgId := c.FormValue("prodImg")
	qrcodeId := c.FormValue("prodQrCode")
	uid := c.FormValue("id")
	id,err := db.EditProduct(title,desc,weight,imgId,qrcodeId,uid)
	
	if err != nil{
		log.Println("EditProduct,err=",err)
		a.Code=-1
		a.Msg=err.Error()
	}else{
		a = Res{
			Code:200,
			Msg:"",
			Result:id,
		}
	}
	return c.JSON(200,a)
}
//删除产品
func DelProduct(c echo.Context) error {
	var a = Res{}
	uid, err := strconv.Atoi(c.FormValue("id"))
	if err != nil {
		log.Println("DelProduct,err=",err)
		a.Code=-1
		a.Msg="参数错误"
		return c.JSON(200,a)
	}

	id,err := db.DelProduct(fmt.Sprint(uid))
	if err != nil{
		log.Println("DelProduct,err=",err)
		a.Code=-1
		a.Msg=err.Error()
	}else{
		a = Res{
			Code:200,
			Msg:"",
			Result:id,
		}
	}
	return  c.JSON(200,a)
}